import React, {PureComponent} from 'react';
import './index.css'

class Parent extends PureComponent {
    state = {
        carName: '奔驰c63'
    }
    changeCar = () => {
        this.setState({carName: '迈巴赫'})   // 可正常使用PureComponent，避免不必要的更新，比如组件引用子组件并无值发生变化
        // 使用以下方式会不发生变化，因为对象地址相同
        // const obj = this.state
        // obj.carName = 'aaa'
        // this.setState(obj)
    }

    // shouldComponentUpdate(nextProps, nextState, nextContext) {
    //     return this.state.carName !== nextState.carName
    // }

    render() {
        console.log('render parent')
        const {carName} = this.state
        return (
            <div className='parent'>
                <h3>我是Parent组件</h3>
                <p>我的车名字是：{carName}</p>
                <button onClick={this.changeCar}>点我换车</button>
                <Child carName={carName}/>
            </div>
        );
    }
}

class Child extends PureComponent {
    // shouldComponentUpdate(nextProps, nextState, nextContext) {
    //     return this.props.carName !== nextProps.carName
    // }

    render() {
        console.log('render child')
        return (
            <div className='child'>
                <h3>我是Child组件</h3>
                <p>我接到的车是：{this.props.carName}</p>
            </div>
        );
    }
}

export default Parent;